<script setup lang="ts">
import {ref, watch} from "vue";
import Taskinput from "@/components/Taskinput.vue";
interface ITaskItem {
  id:number;
  text:string;
  isDone:boolean;
  isEdit:boolean
}
let todoText = ref('');
//是一个响应式对象，可以用来接收字符串，响应型变量，用let进行创建，let来自于vue，

let tasklist = ref<ITaskItem[]>([]);

tasklist.value = JSON.parse(window.localStorage.getItem('taskList')??"[]");
//parse把字符串解释为对象（反串行化）
//??"[]"空中括号代表空数组

watch(tasklist,onSave, {deep:true})
function onAddTask(taskText: string) {
  tasklist.value.push({
    id: tasklist.value.length + 1,
    text: taskText,
    isDone: false,
    isEdit: false
  });
  todoText.value = '';

  // 更新 localStorage 中的数据
  window.localStorage.setItem('taskList', JSON.stringify(tasklist.value));
}

// push()函数
//key--value（串行化）
//key一般是不重复的值
//JSON类似一个文件包，浏览器自带，stringify是一个函数，会把参数转化成JSON对应格式的字符串
// 执行push将添加数据加入末尾

function onSave(){
    window.localStorage.setItem('taskList', JSON.stringify(tasklist.value));
}
let itemText = ref("")
function onEdit(item:ITaskItem){
    item.isEdit = true;
}

function onEditOk(item:ITaskItem){
  item.isEdit = false
  item.text = itemText.value
}

function onDelete(item: ITaskItem){
  tasklist.value = tasklist.value.filter(it=>it!==item);
}
// filter不会改变数组

// function checkItem(item: ITaskItem, it:ITaskItem){
//   return it!=item
// }

</script>

<template>
  <div class="container">
    <h1>ToDo List</h1>

    <Taskinput @addTask="onAddTask"></Taskinput>

    <div class = "task-list">
      <div v-for="item of tasklist" class="task-item">
        <template v-if="!item.isEdit">
<!--        item.text是插值表达式-->
          <el-checkbox v-model="item.isDone" size="large">
            {{ item.text }}
          </el-checkbox>
<!--          v-model进行双向绑定-->
          <div>
            <el-button type="primary" @click="onEdit(item)">修改</el-button>
            <el-button type="danger" @click="onDelete(item)">删除</el-button>
          </div>
        </template>
        <template v-else>
          <el-checkbox v-model="item.isDone" size="large">
            <el-input v-model="itemText"></el-input>
            <el-button @click="onEditOk(item)">确定</el-button>
            <el-button @click="item.isEdit = false">取消</el-button>
          </el-checkbox>
        </template>
      </div>

    </div>


  </div>

</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 80%;
  margin: 0 auto;
  background-color: #f3f3f3;
  }

h1 {
  text-align: center;
  margin-top: 20px;
}


.task-list {
  padding: 0 2em;
}
.task-item {
  display: flex;
  justify-content: space-between;
  align-content: center;
  border-bottom: 1px solid #ccc;
}

</style>
